
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace QQZiFramework.Mvc
{
    public class EndRequestMiddleware
    {
        private readonly RequestDelegate _next;

        public EndRequestMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            context.Request.EnableBuffering();//.EnableRewind();
            await _next(context);
        }


        // public async Task Invoke(HttpContext context)
        // {
        //     var originalResponseStream = context.Response.Body;
        //     using (var ms = new MemoryStream())
        //     {
        //         context.Response.Body = ms;            
        //         context.Request.EnableBuffering();//.EnableRewind();
        //         await _next(context);//执行控制器逻辑
        //         //处理输出（是否需要转繁体)
        //         DBContext dbContext = QQZiFramework.Mvc.Extensions.HttpContext.CurrentWexContext.Context;
        //         bool toTraditional = false;
        //         if (dbContext != null)
        //         {
        //             toTraditional = ((WebHostMemberShip) dbContext.Membership).ResponseTraditional;
        //         }
        //         QQZiFramework.Mvc.Extensions.HttpContext.Clear();
        //         //context.Request.Body.Close();
        //         ms.Position = 0;
        //         if (toTraditional && context.Response.ContentType != null && ( context.Response.ContentType.IndexOf("text/") > -1 || context.Response.ContentType.IndexOf("/json") > -1))
        //         {
        //             StreamReader sr = new StreamReader(ms);
        //             string str = sr.ReadToEnd();
        //             ms.Position = 0;
        //             using (var writer = new StreamWriter(originalResponseStream))
        //             {
        //                 if (toTraditional && str != null && str.Length > 0 && str[0] == '{')
        //                     await writer.WriteAsync(ConvertHelper.ToTraditional(str));
        //                 else
        //                     await writer.WriteAsync(str);
        //                 await writer.FlushAsync();
        //             }

        //         }
        //         else
        //         {
        //             await ms.CopyToAsync(originalResponseStream);
        //         }
        //         context.Response.Body = originalResponseStream;
        //     }

        // }
    }
}